package com.ys.controller.api.base;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.base.TbUserMonthPerformanceReport;
import com.ys.entity.sys.YsCol;
import com.ys.service.base.TbUserMonthPerformanceReportService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 员工月度绩效申报
 */
@Controller
@RequestMapping("/api/inter/tbUserMonthPerformanceReport")
public class ApiInterTbUserMonthPerformanceReportController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTbUserMonthPerformanceReportController.class);

    @Autowired
    private CommonApiService<TbUserMonthPerformanceReport> commonApiService;

    @Autowired
    private TbUserMonthPerformanceReportService tbUserMonthPerformanceReportService;

    @Autowired
    private YspTaskService yspTaskService;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TbUserMonthPerformanceReport setSeachSql(TbUserMonthPerformanceReport cond){
        cond.addLeftJoin("TB_UserMonthPerformanceReportItem I ON I.Pbid = A.Bid")//子表
                .addField("I.MonthPerformanceId AS monthPerformanceId")//员工月度绩效信息表Id
                .addField("I.HrPerformancePoint AS hrPerformancePoint")//人事绩效评分
                .addField("I.HrPerformanceContent AS hrPerformanceContent")//人事绩效内容
                .addField("I.JobBonus AS jobBonus")//岗位提奖
                .addField("I.JobBonusExplain AS jobBonusExplain");//岗位提奖说明

        cond.addLeftJoin("TB_UserMonthPerformance M ON I.MonthPerformanceId = M.Id")//员工月度绩效信息
                .addField("M.Rank AS rank")//岗位职级
                .addField("M.Type AS type")//岗位工种
                .addField("CASE " +
                        "WHEN M.Type = 1 THEN '总经理' " +
                        "WHEN M.Type = 2 THEN '副总经理' " +
                        "WHEN M.Type = 3 THEN '责任月薪型员工' " +
                        "WHEN M.Type = 4 THEN '绩效提奖型员工' " +
                        "WHEN M.Type = 5 THEN '研发人员' " +
                        " ELSE '' END roleLevelTypeTxt")
                .addField("M.PointMonth AS pointMonth");//评定年月

        cond.addLeftJoin("TS_UserInfo U ON U.UserId = M.UserId")//用户信息表
                .addField("(U.UserId + '/' + U.UserName) AS userName")//工号/姓名

                .addLeftJoin("TS_OrganizationInfo OI ON OI.Orgid = U.DeptId")
                .addField("OI.DeptName AS deptName")//部门

                .addLeftJoin("THR_UserArchives UAS ON UAS.UserId = M.UserId")//用户档案表
                .addField("UAS.UserState AS userState")//员工状态
                .addField("CASE " +
                        "WHEN UAS.UserState = 0 THEN '实习' " +
                        "WHEN UAS.UserState = 1 THEN '试用' " +
                        "WHEN UAS.UserState = 2 THEN '正式' " +
                        "WHEN UAS.UserState = 3 THEN '离职' " +
                        " ELSE '' END userStateTxt")//员工状态（0实习、1试用、2正式、3离职）

                .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = M.OrgId")//组织机构表
                .addField("O.OrgName AS orgName");//所属公司

        cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid")
                .addField("CASE " +
                        "WHEN A.EffectStock = 1 THEN FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') " +
                        " ELSE '' END auditingTime");//审核时间
            //.addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime");//审核时间

        cond.addLeftJoin("TS_UserChange C ON C.Id = A.CreateChangeId")
                .addField("(C.UserId + '/' + C.UserName) AS _ys_nameLinked")//制单人
                .addField("C.DeptName AS createDeptName")//制单人部门
                .addField("C.RoleName AS createRoleName");//制单人岗位


        cond.addLeftJoin("TS_UserInfo CU ON CU.UserId = C.UserId")//用户信息表
                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = CU.OrgId");//用户所属机构

        //排序
        cond.setOrderby("A.Bid DESC");
        cond = commonApiService.dataAuth(MenuId.TB_UserMonthPerformanceReport, cond);
        return cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tbUserMonthPerformanceReport:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TbUserMonthPerformanceReport cond,String conditions){
        try {
            cond = setSeachSql(cond);
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_nameLinked");//制单人
            if (nameLinked != null){
                cond.where("C.UserId LIKE '%" + nameLinked + "%'" + " OR  C.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TbUserMonthPerformanceReport cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TB_UserMonthPerformanceReport)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TbUserMonthPerformanceReport> util = new ExportExcelUtils<>(new TbUserMonthPerformanceReport());
            String toFilePath = util.exportExcel(listData, listField, "员工月度绩效申报");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 新增
     */
    @RequiresPermissions("tbUserMonthPerformanceReport:add")
    @RequestMapping("/add")
    @ResponseBody
    public R add(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //保存
            return tbUserMonthPerformanceReportService.save(params,MenuId.TB_UserMonthPerformanceReport);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 编辑
     */
    @RequiresPermissions("tbUserMonthPerformanceReport:add")
    @RequestMapping("/edit")
    @ResponseBody
    public R edit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //保存
            return tbUserMonthPerformanceReportService.save(params,MenuId.TB_UserMonthPerformanceReport);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 流转通过
     */
    @RequiresPermissions("tbUserMonthPerformanceReport:add")
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tbUserMonthPerformanceReportService.flowPass(id, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("流转出错：",e.getMessage(),e);
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 流转驳回
     */
    @RequiresPermissions("tbUserMonthPerformanceReport:add")
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        TbUserMonthPerformanceReport entity = new TbUserMonthPerformanceReport().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("驳回出错：",e.getMessage(),e);
            return R.error("服务器正在开小差，请联系客服");
        }
    }


    /**
     * 流转驳回
     */
    @RequiresPermissions("tbUserMonthPerformanceReport:add")
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        TbUserMonthPerformanceReport entity = new TbUserMonthPerformanceReport().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("驳回出错：",e.getMessage(),e);
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 删除
     */
    @RequiresPermissions("tbUserMonthPerformanceReport:add")
    @RequestMapping("/delete")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            return tbUserMonthPerformanceReportService.del(id);
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 删除列表信息
     */
    @RequiresPermissions("tbUserMonthPerformanceReport:add")
    @RequestMapping("/toDelByItem")
    @ResponseBody
    public R toDelByItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            //删除
            for(int i=0;i<idList.size();i++) {
                tbUserMonthPerformanceReportService.delByItem(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("子表信息删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



}